﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace WindowsGame1
{
    class StateMachine
    {
        private Stack<BaseState> m_StateList = new Stack<BaseState>();

        public void Shutdown()
        {
            foreach (BaseState bs in m_StateList)
                bs.Exit();
            m_StateList.Clear();
        }

        public void ChangeState(BaseState _newState)
        {
            foreach (BaseState bs in m_StateList)
                bs.Exit();
            m_StateList.Clear();
            m_StateList.Push(_newState);
            m_StateList.Peek().Enter();
        }

        public void PushState(BaseState _newState)
        {
            m_StateList.Push(_newState);
            m_StateList.Peek().Enter();
        }

        public void PopState()
        {
            m_StateList.Pop().Exit();
        }

        public void Update(float _delta)
        {
            if (m_StateList.Count != 0)
                m_StateList.Peek().Update(_delta);
        }

        public void Render(SpriteBatch _spriteBatch)
        {
            if (m_StateList.Count > 1)
            {
                BaseState[] tempArray = m_StateList.ToArray();
                int numElements = m_StateList.Count;
                for (int i = numElements - 1; numElements >= 0; i--)
                    tempArray[i].Render(_spriteBatch);
            }
            else if (m_StateList.Count == 1)
            {
                m_StateList.Peek().Render(_spriteBatch);
            }
        }
    }
}
